package org.example.springboot.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.example.springboot.entity.Cycle;
import org.example.springboot.entity.FmcControl;
import org.example.springboot.entity.IrrigationUnit;
import org.example.springboot.entity.PendingTasks;
import org.example.springboot.service.CycleService;
import org.example.springboot.service.FmcControlService;
import org.example.springboot.service.IrrigationUnitService;
import org.example.springboot.service.PendingTasksService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

@Slf4j
@Component
public class CycleCheckHandler {


    @Resource
    private IrrigationUnitService irrigationUnitService;

    @Resource
    private CycleService cycleService;

    @Resource
    private FmcControlService fmcControlService;

    @Resource
    private PendingTasksService pendingTasksService;

    @XxlJob("createCycleCheckHandler")
    public void createCycleCheckHandler(){
        String jobParam = XxlJobHelper.getJobParam();
        long jobId = XxlJobHelper.getJobId();
        log.info("CycleCheckHandler-定时任务已执行，任务ID：{}，参数：{}", jobId, jobParam);

        IrrigationUnit irrigationUnit = irrigationUnitService.getOne(new QueryWrapper<IrrigationUnit>().eq("control_device", jobParam));
        log.info("灌溉单元数据：{}", irrigationUnit);
        Cycle cycle = cycleService.getOne(new QueryWrapper<Cycle>().eq("irrigation_unit_uuid", irrigationUnit.getUuid()));
        log.info("周期数据：{}", cycle);
        //判断对应指标表的ET数据是否大于上限
        String controlDevice = irrigationUnit.getControlDevice();
        log.info("控制设备：{}", controlDevice);
        FmcControl fmcControl = new FmcControl();
        fmcControl.setDid(controlDevice);
        fmcControl.setUnitCode(irrigationUnit.getUnitCode());
        fmcControl.setValt(1);
        fmcControl.setOperationTime(new Date());
        fmcControl.setTopic("FMC_control/" + controlDevice);
        JSONObject message = new JSONObject();
        message.put("project", "FMC_irrigator");
        message.put("device", controlDevice);
        message.put("method", "0");
        message.put("valt1", "1");
        message.put("amount", String.valueOf(cycle.getIrrigationVolume()));
        fmcControl.setMessage(message);
        log.info("开始执行周期灌溉，MQTT消息：{}", message);
        PendingTasks pendingTasks = new PendingTasks();
        pendingTasks.setSort(Integer.valueOf(irrigationUnit.getSym()));
        pendingTasks.setMqttContent(JSONObject.toJSONString(fmcControl));
        pendingTasksService.save(pendingTasks);
        //fmcControlService.sendMessageToMqtt(fmcControl);


    }

}


